<template>
  <div class="cart-con-list pad-t-26">
    <template v-if="!isShowNoneDataView">
      <!-- 内容列表 -->
      <div class="tab-container">
        <div v-loading="listLoading" :element-loading-text="loadingText" element-loading-background="#ffffff"
          class="c-table">
          <template v-if="!listLoading">
            <div class="pad-l-20 pad-r-20 pad-b-20">
              <div class="c-table__head">
                <div class="c-table__td flex-item" style="width: 340px">
                  <div class="flex v-align-c">
                    <el-checkbox v-model="allChecked" class="checkbox-pad" @change="handleAllSelectCart">全选
                    </el-checkbox>
                    <div class="pad-g-t">商品</div>
                  </div>
                </div>
                <div class="c-table__td" style="width: 158px">规格</div>
                <div class="c-table__td" style="width: 161px"><span class="pad-l-2">价格</span></div>
                <div class="c-table__td" style="width: 162px">重量</div>
                <div class="c-table__td" style="width: 202px">数量</div>
                <div class="c-table__td" style="width: 178px"><span class="pad-l-2">小计</span></div>
                <div class="c-table__td" style="width: 143px">操作</div>
              </div>
              <div class="c-table__body mar-t--7">
                <template v-if="cartData.efficientShopList && cartData.efficientShopList.length > 0">
                  <div v-for="(itemShop, indexShop) in cartData.efficientShopList" :key="indexShop"
                    class="c-table__row">
                    <div class="c-row__head">
                      <div class="c-row__left">
                        <div class="c-table__td">
                          <div class="select">
                            <el-checkbox v-model="itemShop.checked" class="checkbox-pad"
                              @change="handleAllSelectShop(itemShop)" />
                          </div>
                          <div>
                            <span>{{itemShop.shopName}}</span>
                          </div>
                          <div class="mar-l-12">
                            <span class="tag-city" v-if="itemShop.areaName">{{itemShop.areaName}}</span>
                          </div>
                        </div>
                      </div>
                      <div class="c-row__right">&nbsp;</div>
                    </div>
                    <div v-for="(itemGoods, itemGoodsIndex) in itemShop.goodsResponseList" :key="itemGoodsIndex"
                      class="c-table__tr align-td-t font-12">
                      <div class="c-table__td flex-item flex v-align-t align-td-t mar-t--3" style="width: 340px">
                        <div class="pad-t-19">
                          <el-checkbox v-model="itemGoods.checked" class="checkbox-pad"
                            @change="handleSelectItemGoods(1,itemShop,itemGoods)" />
                        </div>
                        <img :src="itemGoods.imageUrl" alt="" class="width-80 height-80 mar-r-11">
                        <div class="mar-t--3" style="width: 220px">
                          <div class="_line-1">{{itemGoods.title}}</div>
                          <div class="font-color-6 pad-t-4" v-if="itemGoods.goodsCode">货号：{{itemGoods.goodsCode}}</div>
                        </div>
                      </div>
                      <div class="c-table__td font-color-6" style="width: 158px">
                        {{itemGoods.skuDetail ? itemGoods.skuDetail:''}}
                      </div>
                      <div class="c-table__td font-color-6" style="width: 161px">
                        <div>
                          <div>￥{{itemGoods.distributePrice}}</div>
                          <!-- <div class="tag-11">闪电发货</div> -->
                        </div>
                      </div>
                      <div class="c-table__td font-color-6" style="width: 162px">
                        {{itemGoods.weight ? itemGoods.weight : ''}}
                      </div>
                      <div class="c-table__td" style="width: 202px">
                        <el-input-number v-model="itemGoods.goodsNum" class="input-number" :min="1"
                          @change="handleNumberChange(itemGoods)" :loading="true"
                          :disabled="isOpeartShoppingCartGoodsNumIng" />
                      </div>
                      <div class="c-table__td font-color-3 font-14 font-w" style="width: 178px">
                        ￥{{itemGoods.subTotal}}</div>
                      <div class="c-table__td" style="width: 143px">
                        <el-button type="text" class="remove-btn-t" @click="handleDeleteShoppingCart(itemGoods)">删除
                        </el-button>
                      </div>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <none-data />
                </template>
              </div>
            </div>
            <h2 v-if="cartData.invalidShopList.length" class="fail-t-top"
              :style="backgroundValue ? 'background : ' + backgroundValue : ''">
              已失效商品</h2>
            <div class="pad-l-20 pad-r-20 pad-b-20">
              <div class="c-table__body">
                <div v-for="(itemShop, indexShop) in cartData.invalidShopList" :key="indexShop"
                  class="c-table__row fail-list">
                  <div class="c-row__head">
                    <div class="c-row__left">
                      <div class="c-table__td">
                        <div class="select">
                          <el-checkbox v-model="itemShop.checked" class="checkbox-pad"
                            @change="handleAllSelectShop(itemShop)" />
                        </div>
                        <div>
                          <span>{{itemShop.shopName}}</span>
                        </div>
                        <div class="mar-l-12">
                          <span class="tag-city" v-if="itemShop.areaName">{{ itemShop.areaName }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="c-row__right">&nbsp;</div>
                  </div>
                  <div v-for="(itemGoods, itemGoodsIndex) in itemShop.goodsResponseList" :key="itemGoodsIndex"
                    class="c-table__tr align-td-t font-12">
                    <div class="c-table__td flex-item flex v-align-t align-td-t mar-t--3" style="width: 340px">
                      <div class="pad-t-19">
                        <el-checkbox v-model="itemGoods.checked" class="checkbox-pad"
                          @change="handleSelectItemGoods(2,itemShop,itemGoods)" />
                      </div>
                      <img :src="itemGoods.imageUrl" alt="" class="width-80 height-80 mar-r-11">
                      <div class="mar-t--3" style="width: 220px">
                        <div class="_line-1">{{itemGoods.title}}</div>
                        <div class="font-color-6 pad-t-4" v-if="itemGoods.goodsCode">货号：{{itemGoods.goodsCode}}</div>
                        <div class="font-color-6 pad-t-4" v-if="itemGoods.remark">失效原因：{{itemGoods.remark}}</div>
                      </div>
                    </div>
                    <div class="c-table__td font-color-6" style="width: 158px">
                      {{itemGoods.skuDetail ? itemGoods.skuDetail:''}}
                    </div>
                    <div class="c-table__td font-color-6" style="width: 161px">
                      <div>
                        <div>￥{{itemGoods.distributePrice}}</div>
                        <!-- <div class="tag-11">闪电发货</div> -->
                      </div>
                    </div>
                    <div class="c-table__td font-color-6" style="width: 162px">
                      {{itemGoods.weight ? itemGoods.weight : ''}}
                    </div>
                    <div class="c-table__td" style="width: 202px">
                      <el-input-number v-model="itemGoods.goodsNum" class="input-number disabled" :min="1"
                        :max="itemGoods.remainStock > 100 ? 99 : itemGoods. remainStock" :disabled="true" />
                    </div>
                    <div class="c-table__td font-color-3 font-14 font-w" style="width: 178px">
                      ￥{{ itemGoods.subTotal }}</div>
                    <div class="c-table__td" style="width: 143px">
                      <el-button type="text" class="remove-btn-t" @click="handleDeleteShoppingCart(itemGoods)">删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
        <template v-if="!listLoading">
          <div class="height-6" :style="!affixBoolean ? 'background : ' + backgroundValue : ''"></div>
          <el-affix class="affix" :class="!affixBoolean ? 'fixed' : ''" position="bottom" :offset="0"
            @change="affixChange">
            <div class="settlement-top" :class="!affixBoolean ? 'fixed' : ''"
              :style="!affixBoolean ? 'background : ' + backgroundValue : ''">
              <!-- <div :style="backgroundValue ? 'background : ' + backgroundValue : ''" class="pad-t-6 settlement-top"> -->
              <div class="bgc-white">
                <div class="flex v-align-c height-66 pad-l-30 mar-l-5">
                  <el-checkbox v-model="allChecked" class="checkbox-pad" @change="handleAllSelectCart">全选</el-checkbox>
                  <el-button class="remove-btn mar-l-30" @click="handleDeleteShoppingCart">删除</el-button>
                  <div class="flex-item">&nbsp;</div>
                  <div>已选商品：</div>
                  <div class="font-18 font-w font-price-00B">{{selectedTotalGoodsNum}}</div>
                  <div class="pad-l-6">件</div>
                  <div class="pad-l-26">总价：</div>
                  <div class="font-20 font-w font-price-00B mar-r-30 pad-r-15">￥{{selectedTotalPrice}}</div>
                  <!-- <el-button class="settlement-btn" v-if="selectedTotalGoodsNum > 0">去结算</el-button> -->
                  <!-- 去结算不可操作按钮展示样式 -->
                  <el-button :class="selectedTotalGoodsNum > 0 ? 'settlement-btn' : 'settlement-btn disabled'"
                    :disabled="selectedTotalGoodsNum <= 0" @click="handleOrderCheck">去结算</el-button>
                </div>
              </div>
            </div>
          </el-affix>
        </template>
      </div>
    </template>
    <!-- 空数据展示 -->
    <none-data v-if="isShowNoneDataView" />
    <confirm-dialog ref="confirmDialogRef" :onSure="handleConfirmSure"></confirm-dialog>
  </div>
</template>

<script lang="ts">
  import {
    defineComponent,
    ref,
    onMounted,
    inject
  } from 'vue'
  import {
    useRouter
  } from 'vue-router'
  import {
    getShoppingCartData,
    deleteShoppingCart,
    addOrUpdateShoppingCart
  } from '@/api/shoppingCart/shoppingCart'
  import {
    ElMessage
  } from 'element-plus'
  import {
    useActions
  } from '@/store/utils/useActions'
  import noneData from '@/components/noneData/index.vue'
  import confirmDialog from '@/components/confirmDialog/index.vue'
  export default defineComponent({
    name: 'CartList',
    components: {
      noneData,
      confirmDialog
    },
    props: {
      pCrossBorderOrderType: String
    },
    setup(props) {
      const router = useRouter()
      const cartList = ref( < any > [])
      const listLoading = ref(true)
      const loadingText = ref('加载中...')
      const allChecked = ref(false)
      // 选中的总商品数量
      const selectedTotalGoodsNum = ref(0)
      // 选中的总商品金额
      const selectedTotalPrice = ref(0.00)
      const backgroundValue = inject('backgroundValue')
      const cartData = ref({
        invalidShopList: [],
        efficientSshopList: []
      })
      const crossBorderOrderType = props.pCrossBorderOrderType
      const isShowNoneDataView = ref(false)
      // 当前操作的购物车id集合
      const currentOpeartCartIds = ref([])
      // 是否正在操作购物车商品数量
      const isOpeartShoppingCartGoodsNumIng = ref(false)
      const storeActions: any = useActions('orderCheck', ['setOrderCheckParams'])
      const confirmDialogRef = ref( < any > null)
      const affixBoolean = ref( < boolean > true)
      onMounted(() => {
        storeActions.setOrderCheckParams(null)
        doGetShoppingCartData()
      })
      // 加载购物车数据
      const doGetShoppingCartData = () => {
        let query = {
          crossBorderOrderType: crossBorderOrderType
        }
        loadingText.value = '加载中...'
        getShoppingCartData(query).then(response => {
          listLoading.value = false
          if (response.isError) return
          let efficientShopList = response.data.efficientShopList
          let invalidShopList = response.data.invalidShopList
          if ((!efficientShopList || efficientShopList.length <= 0) && (!invalidShopList || invalidShopList
              .length <= 0)) {
            isShowNoneDataView.value = true
          }
          cartData.value = response.data
          allChecked.value = false
          handleStatisticsPriceOrSelectNum()
        })
      }
      // 处理商品数量变动逻辑
      const handleNumberChange = (itemGoods: any) => {
        if (!isOpeartShoppingCartGoodsNumIng.value) {
          isOpeartShoppingCartGoodsNumIng.value = true
          const goodsParams = [{
            cartId: itemGoods.cartId,
            goodsNum: itemGoods.goodsNum
          }]
          let shoppingCartParams = {
            goodsList: goodsParams,
            // 改变商品数量是否替换：true-替换，false-累加，前端传值后端判断
            changeGoodsNumIsReplace: true
          }
          addOrUpdateShoppingCart(shoppingCartParams).then(response => {
            isOpeartShoppingCartGoodsNumIng.value = false
            if (response.isError) return
            if (response.code === 3000) {
              itemGoods.goodsNum = response.data
              const goodsParams = [{
                cartId: itemGoods.cartId,
                goodsNum: itemGoods.goodsNum
              }]
              shoppingCartParams.goodsList = goodsParams
              addOrUpdateShoppingCart(shoppingCartParams).then(response => {})
            }
            itemGoods.subTotal = (parseInt(itemGoods.goodsNum) * parseFloat(itemGoods.distributePrice))
              .toFixed(2)
            handleStatisticsPriceOrSelectNum()
            ElMessage.success(response.msg)
          }).catch(errorResponse => {
            ElMessage.success('异常')
            isOpeartShoppingCartGoodsNumIng.value = false
          })
        }
      }
      // 删除商品
      const handleDeleteShoppingCart = (itemGoods: any) => {
        currentOpeartCartIds.value = []
        if (itemGoods && itemGoods.cartId) {
          currentOpeartCartIds.value.push(itemGoods.cartId)
        } else {
          currentOpeartCartIds.value = getSelectedCartIds()
        }
        if (currentOpeartCartIds.value.length > 0) {
          confirmDialogRef.value.openConfirm('是否确认要删除吗？')
        } else {
          ElMessage.error('请选择数据')
        }
      }
      // 确认框,回调函数
      const handleConfirmSure = () => {
        if (currentOpeartCartIds.value.length > 0) {
          listLoading.value = true
          loadingText.value = '删除中...'

          console.log('currentOpeartCartIds', currentOpeartCartIds.value)
          deleteShoppingCart(currentOpeartCartIds.value).then(response => {
            if (response.isError) {
              listLoading.value = false
            }
            doGetShoppingCartData()
            handleStatisticsPriceOrSelectNum()
            currentOpeartCartIds.value = []
            ElMessage.success('删除成功')
          })
        }
      }
      // 获取购物车id集合
      const getSelectedCartIds = () => {
        const cartIds = []
        if (cartData.value) {
          if (cartData.value.efficientShopList && cartData.value.efficientShopList.length > 0) {
            cartData.value.efficientShopList.forEach((item) => {
              if (item.goodsResponseList && item.goodsResponseList.length > 0) {
                item.goodsResponseList.forEach((itemGoods) => {
                  if (itemGoods.checked) {
                    cartIds.push(itemGoods.cartId)
                  }
                })
              }
            })
          }
          if (cartData.value.invalidShopList && cartData.value.invalidShopList.length > 0) {
            cartData.value.invalidShopList.forEach((item) => {
              if (item.goodsResponseList && item.goodsResponseList.length > 0) {
                item.goodsResponseList.forEach((itemGoods) => {
                  if (itemGoods.checked) {
                    cartIds.push(itemGoods.cartId)
                  }
                })
              }
            })
          }
        }
        return cartIds
      }
      // 购物车全选
      const handleAllSelectCart = () => {
        if (cartData.value) {
          if (cartData.value.efficientShopList && cartData.value.efficientShopList.length > 0) {
            cartData.value.efficientShopList.forEach((itemShop) => {
              itemShop.checked = allChecked.value ? true : false
              itemShop.goodsResponseList.forEach((itemGoods) => {
                itemGoods.checked = itemShop.checked ? true : false
              })
            })
            handleStatisticsPriceOrSelectNum()
          }
          if (cartData.value.invalidShopList && cartData.value.invalidShopList.length > 0) {
            cartData.value.invalidShopList.forEach((itemShop) => {
              itemShop.checked = allChecked.value ? true : false
              itemShop.goodsResponseList.forEach((itemGoods) => {
                itemGoods.checked = itemShop.checked ? true : false
              })
            })
          }
        }
      }
      // 店铺级别的商品全选
      const handleAllSelectShop = (itemShop: any) => {
        itemShop.goodsResponseList.forEach((item) => {
          item.checked = itemShop.checked ? true : false
        })
        handleStatisticsPriceOrSelectNum()
        checkIsAllChecked()
      }
      // 单选商品选中
      const handleSelectItemGoods = (type: number, itemShop: any, itemGoods: any) => {
        var checkGoodsCount = itemShop.goodsResponseList.filter((item) => item.checked).length
        itemShop.checked = checkGoodsCount === itemShop.goodsResponseList.length
        if (type === 1) {
          handleStatisticsPriceOrSelectNum()
        }
        checkIsAllChecked()
      }
      // 校验是否全部选中
      const checkIsAllChecked = () => {
        // 有效
        const efficientCheckedCount = cartData.value.efficientShopList.filter((itemShop) => itemShop.checked)
          .length
        // 无效
        const invalidCheckedCount = cartData.value.invalidShopList.filter((itemShop) => itemShop.checked).length

        if (efficientCheckedCount === cartData.value.efficientShopList.length && invalidCheckedCount === cartData
          .value.invalidShopList.length) {
          allChecked.value = true
        } else {
          allChecked.value = false
        }
      }
      // 处理统计金额和数量
      const handleStatisticsPriceOrSelectNum = () => {
        selectedTotalGoodsNum.value = 0
        selectedTotalPrice.value = 0.00
        if (cartData.value) {
          const initNum = ref(0)
          const initPrice = ref(0.00)
          if (cartData.value.efficientShopList && cartData.value.efficientShopList.length > 0) {
            cartData.value.efficientShopList.forEach((itemShop) => {
              itemShop.goodsResponseList.forEach((itemGoods) => {
                if (itemGoods.checked) {
                  initNum.value = initNum.value + 1
                  initPrice.value = parseFloat(initPrice.value) + parseFloat(itemGoods.subTotal)
                }
              })
            })
          }
          selectedTotalGoodsNum.value = initNum.value
          selectedTotalPrice.value = initPrice.value.toFixed(2)
        }
      }
      // 去结算
      const handleOrderCheck = () => {
        if (parseInt(selectedTotalGoodsNum.value) > 0) {
          const orderCheckGoodsList = []
          if (cartData.value.efficientShopList && cartData.value.efficientShopList.length > 0) {
            cartData.value.efficientShopList.forEach((itemShop) => {
              itemShop.goodsResponseList.forEach((itemGoods) => {
                if (itemGoods.checked) {
                  var goodsItem = {
                    cartId: itemGoods.cartId,
                    goodsId: itemGoods.goodsId,
                    skuId: itemGoods.skuId,
                    goodsNum: itemGoods.goodsNum
                  }
                  orderCheckGoodsList.push(goodsItem)
                }
              })
            })
            const orderCheckParams = {
              orderCheckGoodsList: orderCheckGoodsList,
              crossBorderOrderType: crossBorderOrderType
            }
            storeActions.setOrderCheckParams(orderCheckParams)
            router.push({
              path: '/buy'
            })
          } else {
            ElMessage.error('请选择要结算的商品!')
          }
        }
      }
      const affixChange = (e: any) => {
        affixBoolean.value = e
      }

      return {
        cartList,
        listLoading,
        loadingText,
        allChecked,
        handleAllSelectShop,
        handleNumberChange,
        backgroundValue,
        cartData,
        isShowNoneDataView,
        handleDeleteShoppingCart,
        handleAllSelectCart,
        handleSelectItemGoods,
        isOpeartShoppingCartGoodsNumIng,
        selectedTotalGoodsNum,
        selectedTotalPrice,
        handleOrderCheck,
        ...storeActions,
        confirmDialogRef,
        handleConfirmSure,
        affixBoolean,
        affixChange
      }
    }
  })
</script>

<style lang="scss" scoped>
  $darkBlue: #182245;
  $detailWidth: 100%;
  $recommendGoodsWidth: 190px;

  .cart-con-list {
    .pad-g-t {
      padding-left: 63px;
    }

    ::v-deep(.affix) {
      // height: auto!important;
      // &.fixed{
      //   height: 66px!important;
      // }
    }

    .tag-city {
      background: $darkBlue;
      color: #fff;
      height: 18px;
      line-height: 18px;
      display: inline-block;
      padding: 0 5px;
    }

    ._line-1 {
      /* line-height: 1.4; */
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      word-break: break-word;
    }

    .tag-11 {
      border: #ff7300 1px solid;
      color: #ff7300;
      padding: 0 2px;
    }

    .fail-t-top {
      font-weight: normal;
      padding: 28px 0 18px 0;
      margin: 0 0px;
      font-size: 16px;
      color: #373737;
      background: #f5f5f5;
    }

    ::v-deep(.remove-btn) {
      &.el-button {
        min-height: 30px;
        padding: 0px 9px;
        border-radius: 2px;
        color: #323233;
      }
    }

    ::v-deep(.settlement-btn) {
      &.el-button {
        color: #ffffff;
        background: #ff500b;
        padding: 0px 0px;
        min-height: 66px;
        width: 160px;
        font-size: 20px;
        font-weight: bold;
        border-radius: 0;
        border: none;

        &.disabled {
          color: #ffffff;
          background: #dddddd;
        }
      }
    }

    ::v-deep(.remove-btn-t) {
      &.el-button {
        color: #666666;
        padding: 0px 0px;
        min-height: auto;
        font-size: 12px;
        margin-top: 3px;
      }
    }

    ::v-deep(.input-number) {
      &.disabled {

        .el-input-number__decrease,
        .el-input-number__increase {
          background: #f5f7fa;
        }
      }

      &.el-input-number {
        width: 102px;
        line-height: 26px;
      }

      .el-input-number__decrease {
        border-right: #eeeeee 1px solid !important;
      }

      .el-input-number__increase {
        border-left: #eeeeee 1px solid !important;
      }

      .el-input-number__decrease,
      .el-input-number__increase {
        position: absolute;
        z-index: 1;
        top: 1px;
        width: 25px;
        height: auto;
        text-align: center;
        background: #ffffff;
        color: #464646;
        font-size: 13px;
        border-right: 0;
        line-height: 24px;
      }

      .el-input {
        line-height: 26px;
        border-right: 0;
        --el-input-border-radius: 0;
      }

      .el-input__inner {
        border-right: 0;
        height: 26px;
        line-height: 26px;
        padding: 0 15px;
        padding-left: 23px;
        padding-right: 23px;
        border: #eeeeee 1px solid;
      }
    }

    .fail-list {
      -webkit-filter: grayscale(100%);
      -moz-filter: grayscale(100%);
      -ms-filter: grayscale(100%);
      -o-filter: grayscale(100%);
      filter: grayscale(100%);
      filter: gray;
      filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
    }

    .settlement-top {
      box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.3);

      &.fixed {
        background: #f5f5f5;
        box-shadow: 0px 0px 0px;
      }
    }
  }
</style>
